package com.getguang.superstore.home.list

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.apollographql.apollo3.api.Optional
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.basic.apollo.ext.optional
import com.starblink.basic.apollo.ext.optionalOrAbsent
import com.starblink.rocketreserver.DiscountMerchantsListV3Query
import kotlinx.coroutines.launch

/**
 *  Create by yuanl at 2023/10/10
 **/
class DealsListVM: BaseViewModel() {

    var deals: Array<String>? = null

    val titleModel = DealsTitleModel(null)

    val contents = mutableListOf<Any>().apply {
        add(titleModel)
        add(DealsLoadingModel(lastIndex))
        add(DealsLoadingModel(lastIndex))
    }

    val dealsLD by lazyOnNone {
        MutableLiveData<Pair<Int, Boolean>>()
    }

    val contentEmptyModel by lazy {
        DealsEmptyModel(contents.lastIndex)
    }

    var pageNo = 1

    //val requestSeed = ((System.currentTimeMillis() % 1000).toInt()).optional()

    var randomSeed: Int? = null

    var defaultImagesIndex: Int? = null

    fun loadData(forMore: Boolean = false) {
        val dealsOpt: Optional<List<String>?> = deals?.toList().optionalOrAbsent()
        if (forMore) {
            pageNo ++
            //dealsOpt = Optional.Absent
        } else {
            pageNo = 1
            //dealsOpt = deals?.toList().optionalOrAbsent()
            randomSeed = null
            defaultImagesIndex = null
        }
        viewModelScope.launch {
            graphQLQuery(DiscountMerchantsListV3Query(
                pageNo = pageNo,
                pageSize = 10,
                randomSeed = randomSeed.optionalOrAbsent(),
                dealIds = dealsOpt,
                home = false.optional(),
                defaultImagesIndex = defaultImagesIndex.optionalOrAbsent()
            ))?.data.let {
                randomSeed = it?.discountMerchantsListV3?.randomSeed
                defaultImagesIndex = it?.discountMerchantsListV3?.defaultImagesIndex
                val list = it?.discountMerchantsListV3?.merchantWebs?.mapNotNull { it?.merchantWebVOF }
                val hasValue = list?.isNotEmpty() == true
                var oldLasIndex = contents.lastIndex
                if (pageNo == 1) {
                    contents.removeLast()
                    contents.removeLast()
                    titleModel.count = it?.discountMerchantsListV3?.discountStoreNum
                    oldLasIndex = 1
                    if (hasValue) {
                        contents.addAll(list!!)
                    } else {
                        contents.add(contentEmptyModel)
                    }
                } else {
                    if (hasValue) {
                        contents.addAll(list!!)
                    }
                }
                dealsLD.postValue(Pair(oldLasIndex, hasValue))
            }
        }
    }


}